<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="证书名称" prop="certName">
        <el-input v-model="queryParams.certName" placeholder="请输入证书名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="证书类型" prop="certValue">
        <el-select v-model="queryParams.certValue" placeholder="请选择证书类型" clearable size="small">
          <el-option v-for="dict in dict.type.sys_cert_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="提醒" prop="isRemind">
        <el-select v-model="queryParams.isRemind" placeholder="请选择提醒" clearable size="small">
          <el-option label="全部" value="" />
          <el-option label="提醒" value="0" />
          <el-option label="不提醒" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['company:certificate:add']">创建</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table fit v-loading="loading" border :data="dataList">
      <el-table-column label="证书名称" prop="certName" min-width="200" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="证书编号/专利号" min-width="200" prop="num" />
      <el-table-column label="是否到期提醒" min-width="200" prop="isRemind">
        <template slot-scope="scope">
          {{
            scope.row.isRemind == "0"
            ? "提醒"
            : scope.row.isRemind == "1"
              ? "不提醒"
              : "--"
          }}
        </template>
      </el-table-column>
      <el-table-column label="广告机是否显示" align="center" width="150">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isAdvShow" :active-value="1" :inactive-value="0"
            @change="handleStatusAdv(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="证书类型" align="center" min-width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_cert_type" :value="scope.row.certValue" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip min-width="250" label="颁发部门" prop="dept">
      </el-table-column>
      <el-table-column label="是否显示" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isShow" active-value="1" inactive-value="0"
            @change="handleStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isTop" active-value="1" inactive-value="0"
            @change="handleIsTop(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column min-width="200" label="有效日期" prop="limitDate">
        <template slot-scope="scope">
          <div v-if="scope.row.limitDate">
            {{ scope.row.limitDate
            }}<span v-if="scope.row.remainDays" :style="{ color: scope.row.remainDays == '已过期' ? 'red' : '' }">({{
  scope.row.remainDays }})</span>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="发证日期/公告时间" prop="publishDate" min-width="220" />
      <el-table-column label="发明人" min-width="100" prop="userName">
        <template slot-scope="scope">
          {{ scope.row.userName || "--" }}
        </template>
      </el-table-column>

      <el-table-column label="经办人" :show-overflow-tooltip="true" prop="operUserName" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.operUserName || "--" }}
        </template></el-table-column>
      <el-table-column :show-overflow-tooltip="true" label="记录" prop="createTime" min-width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.payCount != 0 && scope.row.updateCount != 0">
            <span v-if="scope.row.payCount != 0" style="margin-right: 5px">缴费记录数({{ scope.row.payCount }})</span>
            <span v-if="scope.row.updateCount != 0">更新记录数({{ scope.row.updateCount }})</span>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>

      <el-table-column label="公司基本资料" v-if="$auth.hasPermi('company:certificate:company:change')" align="center"
        min-width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isCompBase" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" v-hasPermi="['company:certificate:info']"
            @click="handleDetail(scope.row.certId)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row.certId)"
            v-hasPermi="['company:certificate:edit']">修改</el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDelete" icon="el-icon-delete"
                v-hasPermi="['company:certificate:remove']">删除</el-dropdown-item>

              <el-dropdown-item v-hasPermi="['company:certificate:log:add:page']" command="addpayLogList"
                icon="el-icon-plus">新增缴费记录</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['company:certificate:log:info']" command="payLogList"
                icon="el-icon-plus">查看缴费记录</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['company:certificate:log:update']" command="updateLog"
                icon="el-icon-plus">更新证书记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改公司公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="elForm" :model="formData" :rules="rules" :disabled="disabled" size="medium" label-width="150px">
        <el-form-item label="证书类型" prop="certValue">
          <el-select v-model="formData.certValue" placeholder="请选择证书类型" clearable :style="{ width: '100%' }">
            <el-option v-for="dict in dict.type.sys_cert_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交申请日" prop="applyDate" v-if="formData.certValue == 2">
          <el-date-picker v-model="formData.applyDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            :style="{ width: '100%' }" placeholder="请选择提交申请日" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="证书名称" prop="certName">
          <el-input v-model="formData.certName" placeholder="请输入证书名称" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="证书编号/专利号" prop="num">
          <el-input :disabled="title !== '创建证书'" v-model="formData.num" placeholder="请输入证书编号/专利号" clearable
            :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <!-- <el-form-item label="证书/专利" prop="certImage">
          <imageUpload
            :fileType="['png', 'jpg', 'jpeg', 'PDF', 'pdf']"
            v-model="formData.certImage"
          />
        </el-form-item> -->
        <el-form-item label="颁发部门" prop="dept">
          <el-input v-model="formData.dept" placeholder="请输入颁发部门" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" type="number" placeholder="请输入排序名称" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <div class="table">
          <el-form-item label="增加表单" prop="form" style="margin-left: 0">
          <el-button type="primary" plain size="mini" @click="handleAddBox">增行</el-button>
          <el-button type="danger" plain size="mini" @click="handleDeleBox">删行</el-button>
          <!-- {{ formData.certItemBos }} -->
          <el-table :data="formData.certItemBos" :border="true" style="width: 100%; ">
            <el-table-column width="180" label="发证日期/公告时间" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`certItemBos.${scope.$index}.publishDate`" :rules="rules.publishDate">
                  <el-date-picker v-model="scope.row.publishDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    :style="{ width: '100%' }" placeholder="请选择发证日期/公告时间" clearable></el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="180" label="有效期" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`certItemBos.${scope.$index}.limitDate`" :rules="rules.limitDate">
                  <el-date-picker v-model="scope.row.limitDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    :style="{ width: '100%' }" placeholder="请选择有效期" clearable></el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column  label="证书附件" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0" :prop="`certItemBos.${scope.$index}.certImage`" :rules="rules.certImage">
                  <FileUpload v-model="scope.row.certImage"></FileUpload>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        </div>
        
        <!-- <el-form-item label="发证日期/ 公告时间" prop="publishDate">
          <el-date-picker
            v-model="formData.publishDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :style="{ width: '100%' }"
            placeholder="请选择发证日期/ 公告时间"
            clearable
          ></el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="有效期" prop="limitDate">
          <el-date-picker v-model="formData.limitDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            :style="{ width: '100%' }" placeholder="请选择有效期" clearable></el-date-picker>
        </el-form-item> -->
        <el-form-item label="">
          <el-checkbox v-model="formData.isRemind" true-label="0" false-label="1">设置到期提醒时间</el-checkbox>
          <el-select v-model="formData.remindType" placeholder="请选择提醒时间" :style="{ width: '100%' }">
            <el-option label="1个月" value="1" />
            <el-option label="2个月" value="2" />
            <el-option label="3个月" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="发明人" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入发明人" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="经办人" prop="operUserName">
          <el-input v-model="formData.operUserName" placeholder="请输入经办人" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="是否有原件" prop="isOriginal">
          <el-radio-group v-model="formData.isOriginal">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="titleLog" :visible.sync="openLog" width="700px" append-to-body>
      <el-table v-if="openLog" fit v-loading="loadingLog" :data="logFlag === 'pay' ? dataPayLogList : dataUpdateLog">
        <template v-if="logFlag === 'pay'">
          <el-table-column label="缴费日期" width="200" prop="payDate" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column label="缴费费用(元)" width="140" prop="fee" />
          <el-table-column label="录入人" prop="createByName" />
          <el-table-column width="200" label="录入时间" prop="createTime">
          </el-table-column>
        </template>

        <template v-if="logFlag === 'update'">
          <el-table-column label="修改人" prop="updateByName">
          </el-table-column>
          <el-table-column width="200" label="录入时间" prop="updateTime">
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" v-hasPermi="['company:certificate:info']"
                @click="handleDetail(scope.row.certId)">查看</el-button>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  certList,
  certAdd,
  certEdit,
  certDel,
  statusChange,
  updateLog,
  payLogList,
  certInfo,
  isTopChange,
  showChange,
  setAdvShow
} from "@/api/company/cert.js";
export default {
  name: "Certificate",
  dicts: ["sys_cert_type"],
  data() {
    return {
      isRemind: 0,
      dataList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      form: {
        status: 0,
        noticeType: "1",
      },
      // 表单校验
      formData: {
        certValue: undefined,
        certName: undefined,
        num: undefined,
        dept: undefined,
        publishDate: null,
        limitDate: null,
        applyDate: null,
        userName: undefined,
        operUserName: undefined,
        remindType: "1",
        isOriginal:1,
        isRemind: "1",
        certItemBos: [{
          certImage: undefined,
          publishDate: undefined,
          limitDate: undefined,
        }]
      },
      rules: {
        certImage: [
          {
            required: true,
            message: "图片不能为空",
            trigger: "change",
          },
        ],
        certValue: [
          {
            required: true,
            message: "请选择证书类型",
            trigger: "change",
          },
        ],
        certName: [
          {
            required: true,
            message: "请输入证书名称",
            trigger: "blur",
          },
        ],
        // num: [
        //   {
        //     required: true,
        //     message: "请输入证书编号/专利号",
        //     trigger: "blur",
        //   },
        // ],
        // dept: [
        //   {
        //     required: true,
        //     message: "请输入颁发部门",
        //     trigger: "blur",
        //   },
        // ],
        // publishDate: [
        //   {
        //     required: true,
        //     message: "请选择发证日期/ 公告时间",
        //     trigger: "change",
        //   },
        // ],
        // limitDate: [
        //   {
        //     required: true,
        //     message: "请选择有效期",
        //     trigger: "change",
        //   },
        // ],
        // applyDate: [
        //   {
        //     required: true,
        //     message: "请选择申请日",
        //     trigger: "change",
        //   },
        // ],
        // userName: [
        //   {
        //     required: false,
        //     message: "请输入发明人",
        //     trigger: "change",
        //   },
        // ],
        // operUserName: [
        //   {
        //     required: false,
        //     message: "请输入经办人",
        //     trigger: "change",
        //   },
        // ],
        // isOriginal:[
        // {
        //     required: true,
        //     message: "请选择是否有原件",
        //     trigger: "change",
        //   },
        // ]
      },
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isRemind: undefined,
        noticeTitle: undefined,
      },
      rowDetail: {},
      detailOPen: false,
      title: "创建证书",
      disabled: false,
      dataUpdateLog: [],
      dataPayLogList: [],
      logParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
      },
      titleLog: "标题",
      openLog: false,
      loadingLog: false,
      logFlag: "",
    };
  },
  created() {
    this.getList();
    if (this.$route.query.add) {
      this.handleAdd();
    }
    if (this.$route.query.isEdit) {
      this.handleUpdate(this.$route.query.id);
    }
    if (this.$route.query.id) {
      this.handleDetail(this.$route.query.id);
    }
  },
  methods: {
    handleAddBox() {
      this.formData.certItemBos.push({
        certImage: undefined,
        publishDate: undefined,
        limitDate: undefined,
      });
    },
    handleDeleBox() {
      if (this.formData.certItemBos.length == 1) return;
      this.formData.certItemBos.pop();
    },
    handleIsTop(row) {
      let text = row.isTop === "1" ? "置顶" : "取消置顶";
      this.$modal
        .confirm('确认要"' + text + '""' + row.certName + '"证书吗？')
        .then(function () {
          return isTopChange(row.certId, row.isTop);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        })
        .catch(function () {
          row.isTop = row.isTop === "0" ? "1" : "0";
        });
    },
    handleStatusAdv(row) {
      let text = row.isAdvShow === 1 ? "显示" : "隐藏";
      this.$modal
        .confirm('确认要"' + text + '""' + row.certName + '"证书吗？')
        .then(function () {
          return setAdvShow(row.certId, row.isAdvShow);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isAdvShow = row.isAdvShow === "0" ? "1" : "0";
        });
    },
    handleStatus(row) {
      let text = row.isShow === "1" ? "显示" : "隐藏";
      this.$modal
        .confirm('确认要"' + text + '""' + row.certName + '"证书吗？')
        .then(function () {
          return showChange(row.certId, row.isShow);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShow = row.isShow === "0" ? "1" : "0";
        });
    },
    handleStatusChange(row) {
      let text = row.isCompBase === "1" ? "设置" : "取消设置";
      this.$modal
        .confirm('确认要"' + text + '""' + row.certName + '"证书吗？')
        .then(function () {
          return statusChange(row.certId, row.isCompBase);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isCompBase = row.isCompBase === "0" ? "1" : "0";
        });
    },
    openlogDialog(title, e) {
      this.logParams = {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
      };
      this.titleLog = title;
      this.logFlag = e;
      this.openLog = true;
    },
    payLogList() {
      this.openlogDialog("缴费记录", "pay");
      this.loadingLog = true;

      payLogList(this.logParams).then((response) => {
        this.dataPayLogList = response.rows;
        this.loadingLog = false;
      });
    },
    updateLog(e) {
      this.openlogDialog("更新记录", "update");
      this.loadingLog = true;
      this.logParams.id = e.num;
      updateLog(this.logParams).then((response) => {
        this.dataUpdateLog = response.rows;
        this.loadingLog = false;
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "updateLog":
          this.updateLog(row);
          break;
        case "payLogList":
          this.payLogList(row);
          break;
        case "addpayLogList":
          this.addpayLogList(row);
          break;

        default:
          break;
      }
    },
    addpayLogList(row) {
      this.$router.push("./addCertificateLog?num=" + row.num);
    },

    /** 提交按钮 */
    submitForm: function () {
      
      if (this.disabled) {
        console.log('return');
        this.open = false;
        return;
      }
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if(this.formData.sort <0){
            this.$modal.msgWarning("排序序号不得为负数");
            return;
          }
          this.formData.limitDate = this.formData.certItemBos[this.formData.certItemBos.length-1].limitDate
          let query = JSON.parse(JSON.stringify(this.formData));
          if (!this.formData.isRemind) {
            query.remindType = "";
          } else {
            if (!query.remindType) {
              this.$modal.msgWarning("请设置提醒时间");
            }
          }
          query.certLabel =query.certValue? this.dict.type.sys_cert_type.find(
            (e) => e.value === query.certValue
          ).label:''
          if (this.formData.certId != undefined) {
            certEdit(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            certAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        } else {
          console.log('有脏东西');
          // this.$modal.msgWarning('请上传证书附件')
        }
      });
    },
    handleDetail(row) {
      this.open = true;
      this.disabled = true;
      this.title = "查看证书";
      certInfo(row).then((res) => {
        this.formData = res.data;
        this.formData.certItemBos = this.formData.certItemVos 
        
      });
      // this.formData = JSON.parse(JSON.stringify(row));
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.disabled = false;

      this.resetForm("elForm");
      certInfo(row).then((res) => {
        this.formData = res.data;
        this.formData.certItemBos = this.formData.certItemVos 
        console.log(this.formData);
      });
      this.open = true;
      this.title = "修改证书";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.certName + '"的数据项？')
        .then(function () {
          return certDel(row.certId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleAdd() {
      this.disabled = false;

      this.resetForm("elForm");
      (this.formData = {
        certValue: undefined,
        certName: undefined,
        num: undefined,
        dept: undefined,
        // publishDate: null,
        limitDate: null,
        isOriginal:1,
        applyDate: null,
        userName: undefined,
        operUserName: undefined,
        remindType: "1",
        isRemind: "1",
        certItemBos: [{
          certImage: undefined,
          publishDate: undefined,
          limitDate: undefined,
        }]
      }),
        (this.open = true);
      this.title = "创建证书";
    },
    cancel() {
      this.open = false;
      this.detailOPen = false;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      certList(this.queryParams).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
<style scoped lang="scss">
.table{
  ::v-deep .el-form-item__content{
  margin-left: 0 !important;
}
}

</style>